import React from "react";
import { useNode } from "@craftjs/core";
import Image from "next/image";
import { ToolbarSection, ToolbarItem } from "../editor";

interface ImgType {
	src?: string;
	width?: number;
	height?: number;
}
/**
 * 图片组件
 * @param width 宽
 * @param height 高
 * @param src 图片地址
 * @returns
 */
export const Img = ({ width, height, src }: ImgType) => {
	const {
		connectors: { connect, drag },
	} = useNode((state) => ({
		state: state,
	}));

	return (
		<Image
			ref={(ref) => {
				connect(drag(ref));
			}}
			width={width}
			height={height}
			src={src}
			// 增加style是因为动态设置上面宽高属性无效
			style={{
				width: Number.isNaN(Number(width)) ? width : `${width}px`,
				height: Number.isNaN(Number(height)) ? height : `${height}px`,
			}}
			alt=""
		/>
	);
};

// 图片编辑区域显示内容（复用已有组件）
const ImageBoxSettings = () => {
	return (
		<>
			<ToolbarSection
				title="Img"
				props={["width", "height", "src"]}
				summary={({ width, height }: any) => {
					return `宽${width || ""}，高${height || ""}`;
				}}
			>
				<ToolbarItem full={true} propKey="width" type="number" label="宽" />
				<ToolbarItem full={true} propKey="height" type="number" label="高" />
				<ToolbarItem full={true} propKey="src" type="text" label="链接" />
			</ToolbarSection>
		</>
	);
};
// 默认值
const ImgDefaultProps = {
	src: "https://mui.com/static/material-ui/react-components/autocomplete-light.png",
	width: 200,
	height: 100,
};
// 组件配置对象
Img.craft = {
	displayName: "Img",
	props: ImgDefaultProps,
	rules: {
		// 可以拖拽
		canDrag: () => true,
	},
	related: {
		// 关联组件，此组件可以共享组件的属性
		toolbar: ImageBoxSettings,
	},
};
